//
//  MapExView.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/9.
//

import SwiftUI
import MapKit
import Combine

import AlertToast


struct MapExView: View {
    @ObservedObject var locationManager = LocationManager.shared
    @ObservedObject var config = MapConfig.shared
    @ObservedObject var vm = ViewModel.shared
    @State var currentLocation =  ViewModel.shared.lastLocation

    @State var service: WebSocketService
    @State var showMapDetail : Bool = true

    @Binding var showCallTaxiView : Bool
    @State var centerCoordinate = ViewModel.shared.lastLocation
    @State var selectedPlace : MKPointAnnotation?
    @State var showToast = false
    @State var toastMessage : String = ""
    @State var paddingLeft = -20.0
    @State var paddingTop = 0.0

   @State private var startCoordinate = ViewModel.shared.startLocation
   @State private var endCoordinate = ViewModel.shared.endLocation

    private let map = MKMapView()
    let timer = Timer.publish(every: 30, on: .main, in: .common).autoconnect()

   @State var servicePhone : String = ""
   @State var serviceWechat : String = ""

   @State private var isQiyuPresented = false

    var body: some View {
        ZStack {
           MapViewWrapper(route: $config.route, centerCoordinate: self.$centerCoordinate, selectedPlace: self.$selectedPlace, showingPlaceDetails: self.$showMapDetail, currentLocation: self.$currentLocation,startCoordinate:self.$endCoordinate,endCoordinate: self.$endCoordinate,mapView: map).ignoresSafeArea(edges:.bottom)


            VStack(alignment: .leading) {
                HStack(alignment: .top) {
//                    VStack {
//                        VStack {
//                            Image("chat").resizable().scaledToFit().frame(width:20, height:20)
//                            Text("在线客服")
//                        }.onTapGesture {
//                           self.isQiyuPresented = true
//                        }.fullScreenCover(isPresented: $isQiyuPresented) {
//                           VStack {
//                              Button {
//                                 self.isQiyuPresented = false
//                              } label: {
//                                  Text("关闭").font(.system(size: 12))
//                              }
//                              QiyuViewController() // 使用 UIViewControllerRepresentable 包装的视图控制器
//                           }
//                        }
//                        // 分割线
//                        Divider().foregroundColor(Color(hex: "#EBEDF5"))
//                            .frame(width: 40, height: 1)
//                            .padding(6)
                        
//                        VStack {
//                            Image("service_phone").resizable().scaledToFit().frame(width:20, height:20)
//                            Text("客服电话")
//                        }.onTapGesture {
//                            print("call service phone number:\(servicePhone)")
//                            guard let number = URL(string: "tel://\(servicePhone)") else { return }
//                            UIApplication.shared.open(number)
//                        }
//                    }.padding(.horizontal, 5)
//                        .padding(.vertical, 8)
//                        .foregroundColor(.black)
//                        .background(.white)
//                        .cornerRadius(5)
//                        .font(.system(size: 10))
//                        .frame(width:52,height:60)
//                        .offset(y:self.paddingTop)

//                    HStack {
//                        Button {
//                            print("return to current location")
//                            NotificationCenter.default.post(name: .gotoCurrentLocation, object: nil)
//
//                        } label: {
//                            Image(systemName: "location.fill").resizable().scaledToFit()
//                                .frame(width: 20,height: 20)
//                                .padding(8)
//                        }
//
//                        .background(.background)
//                        .opacity(0.8)
//                        .cornerRadius(5)
//
//                        Spacer()
//
//                        Text("\(self.centerCoordinate.longitude )")
//                            .padding()
//                            .accentColor(.white)
//
//                        Text("\(self.centerCoordinate.latitude )")
//                            .padding()
//                            .accentColor(.white)
//                    }
//                    .offset(y:-10.0)
//                    .font(.system(size: 10))
                    Spacer()
                }
                .padding(.vertical, 70)
                .padding(.horizontal, 10)
                Spacer()
            }
            .padding(.top, 15)
            .padding(6)
//            .offset(x:self.paddingLeft)
            .onChange(of: vm.language, perform: { newValue in
                if newValue != .Chinese {
                    self.paddingLeft = 5
                    self.paddingTop = 15.0
                } else {
                    self.paddingLeft = -10.0
                    self.paddingTop = 0
                }
            })
            .onAppear() {
                if vm.language != .Chinese {
                    self.paddingLeft = 5
                    self.paddingTop = 15.0
                } else {
                    self.paddingLeft = -10.0
                    self.paddingTop = 0
                }

                if let pos = locationManager.lastLocation?.coordinate {
                    self.centerCoordinate = pos
                }

                  // 获取服务的电话和微信
//               Api.getServiceInfo { r in
//                  switch r {
//                     case .success(let data):
//                        logger.info("getServiceInfo result:\(data)")
//
//                        DispatchQueue.main.sync {
//                           self.servicePhone = data.phone
//                           self.serviceWechat = data.wechatAccount
//                        }
//
//                     case .failure(let err):
//                        logger.info("getServiceInfo error:\(err.localizedDescription)")
//                  }
//               }
            }
            .onReceive(timer) { _ in
                let order = CarOrder.shared
                let pos = ViewModel.shared.lastLocation
                print("\(Date().formatString) 发送客户端位置Send Client Pos......")
                let newPos = pos

                print("send position:\(ViewModel.shared.debugMode) \(newPos)")
                if service.orderState == .waiting || service.orderState  == .running {
                    service.sendPosition(orderId: order.orderId, driverId: order.driverId, pos: newPos)
                }
            }.toast(isPresenting: $showToast){
                AlertToast(displayMode: .hud, type: .regular, title: self.toastMessage,style: .style(backgroundColor: Color.green, titleColor: .white, subTitleColor: .white, titleFont: .system(size: 14), subTitleFont: .system(size: 14)))
            }
            
        }
    }
}
